package netty5.serializable;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * Created by GanJc on 2015/11/21.
 */
public class UserInfo2 implements Serializable {

    private String userName ;

    private int userId ;

    public UserInfo2(String userName, int userId) {
        this.userName = userName;
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public byte [] toByteArray(ByteBuffer buffer){
        buffer.clear();
        byte[] bytes = this.userName.getBytes();
        buffer.putInt(bytes.length);
        buffer.put(bytes);
        buffer.putInt(userId);
        buffer.flip();

        byte [] result = new byte [buffer.remaining()];
        buffer.get(result);
        return result ;
    }

    public static void main(String[] args) throws IOException {
        UserInfo2 tom = new UserInfo2("tom", 11);
        ByteArrayOutputStream outputStream = null;
        ObjectOutputStream objectOutputStream =null;
        int loop = 1000000 ;
        long now = System.currentTimeMillis();
        for (int i = 0; i < loop; i++) {
            outputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(tom);
            objectOutputStream.flush();
            objectOutputStream.close();
            byte[] bytes = outputStream.toByteArray();
            outputStream.close();
        }
        System.out.println("jdk编码耗时:" + (System.currentTimeMillis() - now) +"ms");

        System.out.println("------------------");
        now = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        for (int i = 0; i < loop; i++) {
            tom.toByteArray(buffer);
        }
        System.out.println("code编码耗时:" + (System.currentTimeMillis() - now) +"ms");

    }
}
